package org.luxor.commons.security.component;

import org.luxor.commons.core.utils.HttpContextUtils;
import org.luxor.commons.core.utils.StrKit;
import org.luxor.commons.core.web.data.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.util.MimeTypeUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 身份认证失败处理器
 *
 * @author yanxinming
 */
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private static final Logger log = LoggerFactory.getLogger(RestAuthenticationFailureHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding(StrKit.CHARSET_NAME);
        response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);

        log.warn("当前来源IP:[{}] 登陆失败. 原因:[{}]", HttpContextUtils.getRemoteAddr(request), exception.getMessage());

        R result = new R(401, "登陆失败", exception.getMessage());
        HttpContextUtils.sendJson(response, result);
    }
}
